package com.mystudy.jcu.cyclicBarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * TODO: {@link CyclicBarrier}
 *
 * @author acy
 * @since 2019/06/18 15:35
 */
public class CyclicBarrierTest1 {
	public static void main(String[] args) throws InterruptedException {
		CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
			System.out.println("所有任务结束之后的回调 all finished");
		});
		new Thread(() -> {
			try {
				TimeUnit.SECONDS.sleep(5);
				System.out.println("t1 finished");
				cyclicBarrier.await();
				System.out.println("t2 finished");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
		}).start();

		new Thread(() -> {
			try {
				TimeUnit.SECONDS.sleep(10);
				System.out.println("t2 finished too");
				cyclicBarrier.await();
				System.out.println("t2 finished too");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
		}).start();
		TimeUnit.SECONDS.sleep(6);
		System.out.println("获取等待的线程数" + cyclicBarrier.getNumberWaiting());
		System.out.println("获取设置的线程数" + cyclicBarrier.getParties());
		System.out.println("栅栏是否被破坏" + cyclicBarrier.isBroken());
		//重置栅栏
		TimeUnit.SECONDS.sleep(5);
		cyclicBarrier.reset();
		System.out.println("获取等待的线程数" + cyclicBarrier.getNumberWaiting());
		System.out.println("获取设置的线程数" + cyclicBarrier.getParties());
		System.out.println("栅栏是否被破坏" + cyclicBarrier.isBroken());
	}
}
